<?php
namespace app\admin\service;

use app\model\WorkersUserModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Service;

class WorkersImportService extends Service
{
    public string $message;
    public int $line;

    /**
     * 用户表格规则
     * @return array array[]
     */
    public function getUserConfig(): array
    {
        return [
            [
                'key' => 'A',
                'name' => '身份证号',
                'field' => 'id_card',
                'required' => true
            ],
            [
                'key' => 'B',
                'name' => '姓名',
                'field' => 'name',
                'required' => true
            ],
            [
                'key' => 'C',
                'name' => '岗位类型',
                'field' => 'position_type',
                'required' => false
            ],
            [
                'key' => 'D',
                'name' => '职称',
                'field' => 'position',
                'required' => false
            ],
            [
                'key' => 'E',
                'name' => '性别',
                'field' => 'sex',
                'required' => false
            ],
        ];
    }

    /**
     * 导入教职工信息
     * @param string $path
     * @param array $data
     * @return bool
     */
    public function import(string $path, array $data): bool
    {
        try {
            $ext = '.xlsx';
            $save_name = '/upload/'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            if (!file_put_contents('./public' . $save_name . $ext, file_get_contents($path))) throw new \Exception('文件加载失败！');
            $spreadSheet = IOFactory::load('./public' . $save_name . $ext);
            $sheet = $spreadSheet->getSheet(0);
            $limit = $sheet->getHighestDataRow('A');
            $UserData = [];
            $time = time();
            $UserConfig = $this->getUserConfig();
            for ($i = 4; $i <= $limit; $i++) {
                $UserRowData = [
                    'unit_id' => $data['unit_id'],
                    'time' => $time
                ];
                foreach($UserConfig as $value){
                    $variate = $sheet->getCell($value['key'].$i)->getValue();
                    if (empty($variate) && $value['required'] && $variate !== 0) throw new \Exception($value['name'].'不能为空！');
                    switch ($value['field']){
                        case 'id_card':
                            if (!isIdCard($variate)) throw new \Exception('身份证号格式错误！');
                            $UserRowData[$value['field']] = $variate;
                            break;
                        case 'position_type':
                            $UserRowData[$value['field']] = match ($variate){
                                '教师‌' => 1,
                                '职员‌' => 2,
                                '教学辅助人员' => 3,
                                '工勤人员' => 4,
                                default => 0
                            };
                            break;
                        case 'sex':
                            $UserRowData[$value['field']] = match ($variate){
                                '男' => 1,
                                '女' => 2,
                                default => 0
                            };
                            break;
//                        case 'age':
//                            $age = $time - ($variate * 86400);
//                            $UserRowData['birthday'] = $age;
//                            $UserRowData[$value['field']] = $variate;
//                            break;
                        default:
                            $UserRowData[$value['field']] = $variate??'';
                    }
                }
                $UserData[] = $UserRowData;
            }
            if (!empty($UserData)){
                $id_cards = array_column($UserData,'id_card');
                $WorkersUserModel = new WorkersUserModel();
                $is = $WorkersUserModel->where('id_card','in',$id_cards)->value('id');
                if ($is) throw new \Exception('有重复的身份证号，请重新填写后再上传！');
                $WorkersUserModel->insertAll($UserData,200);
            }
            return true;
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            $this->line = $e->getLine();
            return false;
        }
    }
}